import cache from "@/plugins/cache"
import { difference, assign, uniq, reject } from "lodash"

import { enumGet, enumOptions } from "@/api"

const enumCacheName = "pmc_enums"

let timer
let nameGroup = []
let taskFn = []
let requests = enumGet

/**
 * 获取字典
 * @param name 字典下拉
 * @param callBack 任务回调
 */
const getEnum = (name = [], type = "enums", callBack) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (Array.isArray(name)) {
        nameGroup = [...nameGroup, ...name]
      } else {
        nameGroup.push(name)
      }
      // 将任务挂起。
      if (callBack) taskFn.push(callBack)
      timer && clearTimeout(timer)
      timer = setTimeout(async () => {
        if (!nameGroup.length) resolve({})
        nameGroup = uniq(nameGroup)
        let resEnum = cache.session.getJSON(enumCacheName) || {}
        for (const item of nameGroup) {
          const cacheEnums = getEnumForCache(item)
          if (cacheEnums && cacheEnums.length) resEnum[item] = cacheEnums
        }
        for (const key in resEnum) {
          if (resEnum[key].length == 0) {
            delete resEnum[key]
          }
        }
        const differenceKeys = difference(nameGroup, Object.keys(resEnum))
        if (differenceKeys.length > 0) {
          let params = {}
          if (type == "enums") {
            requests = enumGet
            params = { name: differenceKeys }
          } else {
            requests = enumOptions
            params = { params: differenceKeys }
          }
          const res = await requests(params)
          if (res.code === 200 || res.code === 0) {
            const originEnums = res.data
            resEnum = assign(resEnum, originEnums)
            const tryDiff = difference(nameGroup, Object.keys(resEnum))
            tryDiff.forEach((v) => {
              resEnum[v] = []
            })
          }
        }
        taskFn.forEach((item) => item(resEnum))
        cache.session.setJSON(enumCacheName, resEnum)
        timer = null
        nameGroup.length = 0
        taskFn.length = 0
        resolve(resEnum)
      }, 200)
    } catch (e) {
      reject(e)
    }
  })
}

const getEnumForCache = (name) => {
  const enums = cache.session.getJSON(enumCacheName)
  if (enums) return enums[name]
  return null
}

// 平台
import { getPlatformOptions } from "@/api/public"
const getPlatformOpt = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["platform"]) {
    let { data } = await getPlatformOptions()
    data = data.map((v) => ({ label: v.platform_name, value: v.platform_id }))
    resEnum["platform"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["platform"]
}
// amazon 站点
// import { getPlatformsSites } from "@/api"
import { countryGetList } from "@/api"
const getAmazonSite = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["amazonSite"]) {
    // let { data } = await getPlatformsSites({ platform_ids: [2] })
    let { data } = await countryGetList({ pageSize: 999999, pageNum: 0 })
    data = data.map((v) => ({ label: v.country, value: v.id }))

    let sortList = ["US", "JP", "CA", "DE", "IT", "AU", "UK", "GB"]
    let amazonSite1 = data.filter((v) => sortList.includes(v.label))
    amazonSite1.sort((a, b) => sortList.indexOf(a.label) - sortList.indexOf(b.label))
    let amazonSite2 = data.filter((v) => !sortList.includes(v.label))
    data = amazonSite1.concat(amazonSite2)
    console.log(19191919189);
    console.log(data);
    
    resEnum["amazonSite"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["amazonSite"]
}

// 仓库属性
import { apiGetWarehouseEnum } from "@/api"
const getWmsAttribute = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["wmsAttribute"]) {
    let data = (await apiGetWarehouseEnum())?.data?.wms_attribute
    resEnum["wmsAttribute"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["wmsAttribute"]
}

// 仓库
import { getWarehouseOptions } from "@/api/public"
const getWarehouse = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["warehouse"]) {
    let { data } = await getWarehouseOptions({ status: 1 })
    resEnum["warehouse"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["warehouse"]
}

// 供应商  数据量太大
// import { getSupplie } from "@/api"
// const getSupplies = async () => {
//   let resEnum = cache.session.getJSON(enumCacheName) || {}
//   if (!resEnum["supplie"]) {
//     let { data } = await getSupplie()
//     resEnum["supplie"] = data
//   }
//   cache.session.setJSON(enumCacheName, resEnum)
//   return resEnum["supplie"]
// }

const optionApiConfig = {
  platform: getPlatformOpt,
  amazonSite: getAmazonSite,
  wmsAttribute: getWmsAttribute,
  warehouse: getWarehouse,
  // supplie: getSupplies,
}

const getAloneEnum = async (keys) => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  let res = {}
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i]
    if (!resEnum[key]) {
      console.log(optionApiConfig)
      resEnum[key] = await optionApiConfig?.[key]()
    }
    res[key] = resEnum[key]
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return res
}

export { getEnum, getAloneEnum, getAmazonSite, getWmsAttribute, getWarehouse }
